﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LingHaoSqlScriptHelperTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dlg.SelectedPath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox2.Text = "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var sqlcon = richTextBox1.Text;
            if (string.IsNullOrEmpty(sqlcon))
            {
                MessageBox.Show("请输入数据库连接字符串。");
                return;
            }
            var sql = richTextBox2.Text;
            if (string.IsNullOrEmpty(sql) || sql.StartsWith("需要导出的SQL语句"))
            {
                MessageBox.Show("请输入需要导出的SQL语句。");
                return;
            }
            var filepath = textBox1.Text;
            if (string.IsNullOrEmpty(filepath))
            {
                MessageBox.Show("请输入SQL脚本存放路径。");
                return;
            }

            try
            {
                Task.Run(() =>
                {
                    生成脚本(sqlcon, filepath, sql);
                });
                button3.Enabled = false;
            }
            catch (Exception ex)
            {
                button3.Enabled = true;
                MessageBox.Show("未知异常：" + ex.Message);
            }
        }

        public void 生成脚本(string connStr, string filepath, string sqltext)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    var sqls = sqltext.Split(';');
                    List<TableInfo> tableInfos = new List<TableInfo>();
                    foreach (var sql in sqls)
                    {
                        if (sql.IsNullOrWhiteSpace_Lh())
                        {
                            continue;
                        }
                        var tablename = Helper.Get截取表名(sql);
                        if (tablename.IsNullOrWhiteSpace_Lh())
                        {
                            MessageBox.Show("数据库表名读取失败，请确认是否符合要求。");
                            return;
                        }
                        this.Invoke(new Action(() =>
                        {
                            label4.Text = "当前进度：" + tablename;
                        }));
                        TableInfo tableInfo = new TableInfo();
                        tableInfo.TableName = tablename;
                        tableInfo.TableDatas = new List<TableData>();
                        using (SqlCommand command = new SqlCommand(sql, conn))
                        {
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                var sch = reader.GetSchemaTable();
                                Dictionary<string, string> columns = new Dictionary<string, string>();
                                foreach (DataRow item in sch.Rows)
                                {
                                    if (item["ColumnName"].ToString() == "DateTimeStamp")
                                    {
                                        continue;
                                    }
                                    columns.Add(item["ColumnName"].ToString() ?? "", item["DataTypeName"].ToString());
                                }

                                var index = 1;
                                while (reader.Read())
                                {
                                    foreach (var column in columns)
                                    {
                                        TableData tableData = new TableData();
                                        tableData.index = index;
                                        var value = reader[column.Key].ToString();
                                        tableData.Name = column.Key;
                                        tableData.Value = Helper.Is根据类类型处理值(column.Value ?? "", value ?? "");
                                        tableInfo.TableDatas.Add(tableData);
                                    }
                                    index++;
                                }
                            }
                        }
                        tableInfos.Add(tableInfo);
                    }

                    if (checkBox1.Checked)
                    {
                        foreach (var item in tableInfos)
                        {
                            var sqlall = Helper.生成Insert语句(item);
                            var path = Path.Combine(filepath, $"{item.TableName}_{DateTime.Now:ffff}.sql");
                            Helper.生成脚本(path, sqlall);
                        }
                    }
                    else
                    {
                        var sqlall = "";
                        foreach (var item in tableInfos)
                        {
                            sqlall = sqlall + "\r\n" + Helper.生成Insert语句(item);
                        }
                        var path = Path.Combine(filepath, $"InsertSql_{DateTime.Now:ffff}.sql");
                        Helper.生成脚本(path, sqlall);
                    }
                }

                MessageBox.Show("生成成功");
                this.Invoke(new Action(() =>
                {
                    label4.Text = "当前进度：无";
                    button3.Enabled = true;
                }));
                return;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = AppDomain.CurrentDomain.BaseDirectory;
        }
    }
}
